<template>
  <div class="page-view">
    <div class="poster-img-wp">
      <h3 class="title">
        长按图片分享
      </h3>
      <img
        v-if="posterUrl"
        :src="posterUrl"
        class="poster-pic"
      >
      <div
        v-else
        class="poster-pic"
      />
      <div
        class="share-btn"
        @click="callShare"
      >
        分享
      </div>
    </div>
    <div
      v-if="!hidePosterDiv"
      class="padding"
    />
    <div
      ref="poster"
      class="poster-div"
    >
      <!-- :style="{width: width + 'px', height: height + 'px'}" -->
      <SharePosterTemplate1
        :logo-url="logoUrl"
        :qrcode-url="qrcodeUrl"
        :share-info="shareInfo"
        :user-status="userStatus"
        @templateLoaded="onTemplateLoaded"
      />
    </div>
    <div
      v-if="isWxQQ"
      class="tip"
      @click="isWxQQ = false"
    >
      <img
        src="~assets/share/share-tip.png"
        class="tip-pic"
      >
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "~scss/others/poster.scss";
@function posterSize($px) {
  @return $px * 2px;
}
// .page-view {
//   overflow: auto;
// }
// .poster-img-wp {
//   display: none;
// }
.poster-div {
  // display: flex;
  // flex-direction: column;
  // justify-content: space-between;
  background: #f0f0f0;
  // align-items: center;
  padding: posterSize(60) 0;
  width: posterSize(750);
  // transform: scale(0.5);
  // transform-origin: 0 0;
}
</style>

<script lang="ts">
import Vue from 'vue'
import QRCode from 'qrcode'
import domtoimage from 'dom-to-image-more'
import { imgToBase64 } from 'lib/utils'
import { loading } from '@/lib/appMethods'
import { showShare } from 'lib/share/share'
import { mapState } from 'vuex'
import { isAndroid } from '@/lib/utils'
import { getShareInfo } from '@/lib/share/shareInfo'
export default Vue.extend({
  components: {
    SharePosterTemplate1: () => import('components/Share/SharePosterTemplate1.vue'),
  },
  data () {
    const { url: path, name: fromName, subj, uname } = this.$route.query
    const config = getShareInfo({
      routeName: fromName as string,
      subject: subj as string,
      userName: uname as string,
      sharePath: path as string,
    })
    return {
      posterUrl: '',
      logoUrl: '',
      qrcodeUrl: '',
      shareData: {
        ...config,
        imgUrl: this.$store.state.instInfo.SchoolH5Logo,
        from: 'jggw',
      },
      isWxQQ: false,
      // width: window.screen.width * 2,
      // height: window.screen.width / 375 * 1334,
      hidePosterDiv: false,
      shareInfo: {},
      traningContent: this.$store.state.instInfo.Industry.join('、'),
      userStatus: 0,
      canStartDraw: false,
    }
  },
  computed: {
    ...mapState(['instInfo']) as MappedState,
  },
  beforeRouteLeave (to, from, next) {
    loading.hide()
    next()
  },
  mounted () {
    loading.show('生成海报中...')
    Promise.all([this.imgToBase64(), this.fetchShareInfo(), this.fetchUserStatus()])
      .then(() => {
        setTimeout(() => {
          console.log('start draw')
          this.drawPoster()
        }, 50)
      })
  },
  methods: {
    onTemplateLoaded () {
      console.log('onTemplateLoaded start draw')
      this.drawPoster()
    },
    fetchUserStatus () {
      return new Promise(resolve => {
        const { buyClassStatus, UserId } = this.$store.state.userInfo
        if (UserId === '-1') {
          this.userStatus = -1
          resolve()
        } else if (buyClassStatus === 1) {
          this.userStatus = 1
          resolve()
        }
      })
    },
    imgToBase64 () {
      if (!this.instInfo.SchoolLogo) {
        return
      }
      return imgToBase64(this.instInfo.SchoolLogo!).then(res => {
        this.logoUrl = res
      })
    },
    fetchShareInfo () {
      return this.$axios({
        url: 'User/ShareInfo',
        method: 'get',
      }).then(res => {
        this.$set(this.$data, 'shareInfo', res)
        // this.traningContent = res.Industry.join('、')
        // const userId = this.$store.state.userInfo.UserId
        // let shareLink = this.shareData.link
        // if (userId !== '-1') {
        //   shareLink += (shareLink.indexOf('?') > -1 ? '&' : '?') + `userId=${userId}`
        // }
        // this.$set(this.$data.shareData, 'link', shareLink)
      }).then(() => {
        return this.generateQrcode()
      }, () => {
        // TODO:WW 删除
        return this.generateQrcode()
      })
    },
    generateQrcode () {
      return QRCode.toDataURL(this.shareData.link, {
        width: 270,
        margin: 0,
      }).then(url => {
        this.qrcodeUrl = url
      }).catch(err => {
        console.log(err)
      })
    },
    drawPoster () {
      if (!this.canStartDraw) {
        this.canStartDraw = true
        return
      }
      console.log('real start draw')
      // if (isAndroid) {
      //   domtoimage.toJpeg(this.$refs.poster).then((dataUrl: string) => {
      //     this.setPosterUrl(dataUrl)
      //   }, (e: any) => {
      //     console.log('poster eerrr', e)
      //     this.setPosterUrl()
      //   })
      // } else {
      // domtoimage
      domtoimage.toSvg(this.$refs.poster).then((dataUrl: string) => {
        // 后面的替换解决ios乱码，转为unicode
        this.base64ToPic(dataUrl.substr(33)
          .replace(/(\s*%0A\s*)|(-webkit-[^;]+;)/g, '')
          // eslint-disable-next-line no-control-regex
          .replace(/[^\x00-\xff]/g, (m) => `&#${m.charCodeAt(0)};`)
        )
      })
      // html2canvas
      // html2canvas(this.$refs.poster as HTMLElement).then((canvas) => {
      //   loading.hide()
      //   this.posterUrl = canvas.toDataURL()
      // })
      // }
    },
    base64ToPic (svg: string) {
      this.$axios({
        url: 'Setting/ConvertShareImg',
        data: {
          Content: svg,
        },
      }, 1).then(res => {
        this.setPosterUrl(res)
      }, () => {
        this.setPosterUrl()
      })
    },
    setPosterUrl (dataUrl?: string) {
      this.hidePosterDiv = true
      loading.hide()
      if (dataUrl) {
        this.posterUrl = dataUrl
      } else if (this.$route.name === 'poster') {
        this.$toast('海报加载失败请刷新重试！')
      }
    },
    callShare () {
      // 唤起浏览器原生分享组件(如果在微信中不会唤起，此时call方法只会设置文案。类似setShareData)
      const platform = showShare(this.shareData)
      if (platform === 'wx' || platform === 'qq') {
        this.isWxQQ = true
      } else if (platform === 'others') {
        this.$dialog.alert({
          message: '请使用您浏览器中自带的分享功能',
        })
      }
    },
  },
})
interface MappedState {
  instInfo: () => InstInfo
  [k: string]: any
}
</script>
